//
//  M4EmailDropUpMenue.swift
//  M4
//
//  Created by 蓝应伟 on 2024/8/12.
//

import UIKit

let cellHeight : CGFloat = 44.0
let defaultHeight : CGFloat = 300

class  M4EmailDropUpMenue: UIView, UITableViewDataSource, UITableViewDelegate {
    private let cellIdentifier = "M4EmailDropUpMenueCell"
      private var tableView: UITableView!
      var data: [String]?{
        didSet{
            guard data != nil else { return }
            tableView.reloadData()
        }
      }
      private var didSelectItemHandler: ((String) -> Void)?
      private var backgroundView: UIView!
      private var tapGesture: UITapGestureRecognizer!
      private var targetView: UIView!
      private var menuHeight: CGFloat = 0

    init(frame: CGRect, data: [String], targetView: UIView) {
        super.init(frame: frame)

        self.data = data
        self.targetView = targetView

        // 创建UITableView
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorInset = UIEdgeInsets.zero
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
        tableView.separatorStyle = .none
        tableView.layer.masksToBounds = true
        tableView.layer.cornerRadius = 8
        tableView.layer.borderWidth = 2
        tableView.layer.borderColor = UIColor.black.withAlphaComponent(0.1).cgColor
        tableView.layer.shadowColor = UIColor.black.cgColor
        tableView.layer.shadowOffset = CGSize(width: 2, height: 2)
        tableView.layer.shadowOpacity = 3
        tableView.layer.shadowRadius = 2.0

        addSubview(tableView)

        // 创建半透明背景视图
        backgroundView = UIView(frame: UIScreen.main.bounds)
        backgroundView.backgroundColor = UIColor.clear

        // 创建点击手势识别器
        tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundViewTapped))
        backgroundView.addGestureRecognizer(tapGesture)
    }
     
     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
     
     // MARK: - UITableViewDataSource
     
     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return data?.count ?? 0
     }
     
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
         let number = data?[indexPath.row]
         cell.textLabel?.text = number
         cell.textLabel?.font = UIFont.systemFont(ofSize: 12)
         cell.textLabel?.textAlignment = .left
         return cell
     }


     // MARK: - UITableViewDelegate
     
     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         guard let selectedItem = data?[indexPath.row] else { return }
         print("选中的：\(selectedItem)")
         didSelectItemHandler?(selectedItem)
     }
     
    func showMenu(from view: UIView, X: CGFloat? = nil, Y: CGFloat? = nil, width: CGFloat? = nil, height: CGFloat? = nil, didSelectItemHandler: @escaping (String) -> Void) {
        self.didSelectItemHandler = didSelectItemHandler
        
        if let window = UIApplication.shared.windows.first {
            // 添加半透明背景视图
            window.addSubview(backgroundView)
            
            // 计算菜单的位置和大小
            let menuOrigin = CGPoint(x: view.center.x - (width ?? view.frame.width) / 2, y: view.frame.origin.y - 40)
            var menuFrame: CGRect
            
            if let X = X, let Y = Y, let width = width, let height = height {
                let dynamicHeight = CGFloat(data?.count ?? 0) * cellHeight > defaultHeight ? defaultHeight : CGFloat(data?.count ?? 0) * cellHeight
                menuFrame = CGRect(x: X, y: Y - (height + 40), width: width, height: dynamicHeight)
            } else {
                if let width = width, let height = height {
                    menuFrame = CGRect(x: menuOrigin.x, y: menuOrigin.y, width: width, height: height)
                } else {
                    let dynamicWidth = width ?? view.frame.width
                    let dynamicHeight = height ?? CGFloat(data?.count ?? 0) * cellHeight
                    menuFrame = CGRect(x: menuOrigin.x, y: menuOrigin.y, width: dynamicWidth, height: dynamicHeight)
                }
            }
            
            frame = menuFrame
            tableView.frame = CGRect(x: 0, y: 0, width: menuFrame.width, height: menuFrame.height)
            
            window.addSubview(self)
        }
    }

    
     func hideMenu() {
         backgroundView.removeFromSuperview()
         removeFromSuperview()
     }
     
     // MARK: - Private Methods
     
     @objc private func backgroundViewTapped() {
         hideMenu()
     }
}
